package com.gin.no_gay_alliance.adpter.user;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import com.gin.common.utils.TimeUtils;
import com.gin.no_gay_alliance.adpter.TimestampAdapter;
import com.gin.no_gay_alliance.adpter.base.BaseBindingRecyclerViewAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.databinding.DialogIpLocationTimestampBinding;
import com.gin.no_gay_alliance.databinding.ItemIpLocationGroupBinding;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.viewmodel.IpLocationHistoryGroup;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/12/26 15:45
 **/
public class IpLocationHistoryGroupAdapter extends BaseBindingRecyclerViewAdapter<ItemIpLocationGroupBinding, IpLocationHistoryGroup> implements View.OnClickListener {

    public IpLocationHistoryGroupAdapter(Context context) {
        super(context);
    }

    public IpLocationHistoryGroupAdapter(@NonNull Context context, @NonNull List<IpLocationHistoryGroup> data) {
        super(context, data);
    }

    /**
     * 绑定数据
     *
     * @param holder
     * @param b        绑定对象
     * @param position 位置
     * @param item
     */
    @Override
    protected void onBindViewHolder(ViewHolder<ItemIpLocationGroupBinding> holder,
                                    @NonNull ItemIpLocationGroupBinding b, int position, IpLocationHistoryGroup item) {
        String start = TimeUtils.format(item.start, TimeUnit.SECONDS, TimeUtils.SHORT_FORMATTER);
        String end = TimeUtils.format(item.end, TimeUnit.SECONDS, TimeUtils.SHORT_FORMATTER);

        b.tvDuration.setText(String.format("%s ~ %s", start, end));
        b.tvIpLocation.setText(item.ipLocation);

        //todo 点击显示分组时间戳
        b.getRoot().setOnClickListener(this);
        b.getRoot().setTag(item);
    }

    /**
     * Called when a view has been clicked.
     *
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        IpLocationHistoryGroup item = (IpLocationHistoryGroup) v.getTag();
        DialogIpLocationTimestampBinding b = MyApplication.app.managerFactory.getViewBindingManager().getDialogView(DialogIpLocationTimestampBinding.class, context);
        b.rv.setAdapter(new TimestampAdapter(context, item.timestamps));
        AlertDialog dialog = AlertDialogUtils.showConfirm(context, item.ipLocation, null, b.getRoot(), null);
        dialog.setOnDismissListener(d -> {
            ViewGroup parent = (ViewGroup) b.getRoot().getParent();
            parent.removeView(b.getRoot());
        });
    }
}
